// 获取总合计
function getTotal(url,totalObj,params){
    return new Promise((resolve,reject)=>{
        layui.use('form', function () {
            var searchForm = form.val("searchForm");
            if(Object.keys(totalObj).length !== 0){
                Object.keys(totalObj).forEach(item=>{
                    totalObj[item] = ''
                })
                setPrice(totalObj)
            }
            Ajax(url, {...searchForm,...params}).then(result => {
                setPrice(result.data)
                resolve(result.data)
            });
        });
    });
}

// layui layer弹层
function layerOpen(option){
    let {type,title,btn=['确定', '取消'],maxHeight=500,content,success,yes,formTemplateName,tableName} = option
    layui.use(["form", "layer","table"], function () {
        var form = layui.form,
            layer = layui.layer,
            table = layui.table;
        layer.open({
            type,
            title,
            btn,
            maxHeight,
            content,
            success:function(){
                success()
            },
            yes: function(layMask){
                let data = form.val(formTemplateName)
                yes(data,layMask).then(()=>{
                    table.reloadData(tableName);
                    layer.close(layMask)
                })
            }
        });
    });
}


/**
 * 表单数据反序列化成对象 
 * @param formData
 * @example 
 * let formObject = $('[name = task-form]').serializeArray();
   let formData = getFormData(formObject);
   console.log(formData)
 * @returns {{}}
 */
   function getFormData(formData) {
    let data = {}
    $.each(formData, function (index, item) {
        data[item.name] = item.value
    })
    return data;
}
/**
 * 展示图片
 * @param   {t} this   点击的this
 */
function showimg(t) {
    // layer.open({
    //     type: 1,
    //     title: false,
    //     closeBtn: 1,
    //     skin: 'layui-layer-nobg', //没有背景色
    //     shadeClose: true,
    //     area: ['50%','100%'],
    //     maxWidth:'400',
    //     content: '<img style="display: inline-block; width: 100%; height: 100%;" src="'+t.src+'">'
    // });
    layer.photos({
        photos: {
            "title": "图片", //相册标题
            "id": 123, //相册id
            "start": 0, //初始显示的图片序号，默认0
            "data": [   //相册包含的图片，数组格式
              {
                "alt": "图片",
                "pid": 1, //图片id
                "src": t.src, //原图地址
                "thumb": t.src //缩略图地址
              }
            ]
        }
        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    });
}

/**
 * 计算百分比
 * @param   {number} num   分子
 * @param   {number} total 分母
 * @returns {number} 返回数百分比
 */
function Percentage(num, total) { 
    if (num == 0 || total == 0){
        return 0;
    }
    return (Math.round(num / total * 10000) / 100.00);// 小数点后两位百分比
}
/**
 * 计算人均值
 * @param   {number} num   分子
 * @param   {number} total 分母
 * @returns {number} 返回值
 */
 function perCapita(num, total) { 
    if (num == 0 || total == 0){
        return 0;
    }
    return (num / total).toFixed(2);
} 
/**
 * 导出
 * @param   {number} url   地址
 * @param   {number} params 参数
 */
function derive(url, params) { 
    window.open('_black').location = `${url}?${params}&token=${token}`
} 

/**
 * 对象转url参数
 * @returns {{}}
 */
function objectToQuery() {
    let obj = arguments[0];
    let prefix = arguments[1];
    if (typeof obj !== "object") return "";
    const attrs = Object.keys(obj);
    return attrs.reduce((query, attr, index) => {
        // 判断是否是第一层第一个循环
        if (index === 0 && !prefix) query += "?";
        if (typeof obj[attr] === "object") {
            const subPrefix = prefix ? `${prefix}[${attr}]` : attr;
            query += this.objectToQuery(obj[attr], subPrefix);
        } else {
            if (prefix) {
                query += `${prefix}[${attr}]=${obj[attr]}`;
            } else {
                query += `${attr}=${obj[attr]}`;
            }
        }
        // 判断是否是第一层最后一个循环
        if (index !== attrs.length - 1) query += "&";
        return query;
    }, "");
}

// tip提示
function tips(elem,tip_elem,tip){
    $(elem).on('mouseover', function(){
        layer.tips(tip,tip_elem, {
            time:2000,
            tips: 1
        });
    });
}

//时间格式化
function dayjsFormat(time,type = true){
    if(time){
        let date = new Date(time*1000);
        let year = date.getFullYear();
        let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        let second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        let alltime = type ? `${year}-${month}-${day} ${hour}:${minute}:${second}` : `${year}-${month}-${day}`
        return alltime;
    }else{
        return ''
    }
}

// 获取浏览器参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];return null;
}


// 替换
function formatValues(value,str=','){
    let text = value;
    text = text.replace(/\r\n/g,str)//兼容i7、i8
    text = text.replace(/\n/g,str); //i9及以上
    
    text = text.replace(/\s/g,str);//替换所有的空格（中文空格、英文空格都会被替换）
    return text
}

// 复制内容
function copyContent(elem){
    let text = $(elem).data('value')
    var oInput = document.createElement('input');//创建一个input标签
    oInput.value = text;//设置value属性
    document.body.appendChild(oInput);//挂载到body下面
    oInput.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
    oInput.className = 'oInput';
    oInput.style.display='none';
    layer.msg('复制成功');
}

// 水印
function setCard(userInfo) {
    let can = document.createElement("canvas");
    can.width = 300;
    can.height = 100;
    let cans = can.getContext("2d");
    cans.beginPath();
    cans.rotate((-10 * Math.PI) / 180);
    cans.font = "18px Arial";
    cans.fillStyle = "#b9b9b9";
    cans.setFillStyle = "#b9b9b9";
    cans.fillText(userInfo.WWID, 10, 50);
    cans.fillText(userInfo.Name, 10, 80);
    // cans.fillText("内部使用，不得外传", 50, 110);
    cans.fill();
    cans.closePath();
    let div = document.createElement("div");
    div.classList.add("watermark")
    div.style.pointerEvents = "none";
    div.style.top = "30px";
    div.style.left = "0px";
    div.style.position = "fixed";
    div.style.zIndex = "499";
    div.style.textAlign = "center";
    div.style.width = document.documentElement.clientWidth + "px";
    div.style.height = document.documentElement.clientHeight + "px";
    div.style.background =
        "url(" + can.toDataURL("image/png") + ") left top repeat";
    div.style.opacity = ".2";
    document.body.appendChild(div);
}

function debounce(func, delay) {
    let timerId;
    
    return function() {
        const context = this;
        const args = arguments;
        
        clearTimeout(timerId);
        timerId = setTimeout(() => {
            func.apply(context, args);
        }, delay);
    };
}